package com.zt.dev.standardManage.utils;

import com.zt.dev.standardManage.entity.enmu.CategoryEnum;
import com.zt.dev.standardManage.entity.vo.Standards;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 导出XML文件
 */
public class Dom4jXML {

    /**
     * 生成xml方法
     */
    public XMLWriter createXml(String fileName,List<Standards> standardsList){
        XMLWriter writer = null;
        try{
            //创建document对象
            Document document = DocumentHelper.createDocument();
            //创建根节点rss
            Element rss = document.addElement("rss");
            //向rss添加version属性
            rss.addAttribute("version","2.0");
            //填值
            for(Standards standards : standardsList){
                //生成子节点及子节点内容
                Element channel = rss.addElement("评估准则");
                Element standardName = channel.addElement("准则名称");
                Element target = channel.addElement("评估对象");
                Element context = channel.addElement("准则内容");
                Element method = channel.addElement("评估方法");
                Element category = channel.addElement("准则类别");
                Element creater = channel.addElement("创建人");
                Element createTime = channel.addElement("创建时间");
                standardName.setText(standards.getStandardName());
                context.setText(standards.getContext());
                target.setText(standards.getTarget());
                method.setText(standards.getMethod());
                category.setText(CategoryEnum.getType(standards.getCategoryNode()));
                creater.setText(standards.getCreater());
                createTime.setText(standards.getCreateTime());
            }
            //设置生成xml的格式
            OutputFormat format = OutputFormat.createPrettyPrint();
            //设置编码格式
            format.setEncoding("UTF-8");
            //生成xml文件
            File file = new File(fileName);
            writer = new XMLWriter(new FileOutputStream(file), format);
            //设置是否转义，默认使用转义字符
            writer.setEscapeText(false);
            writer.write(document);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            File file = new File(fileName);
            file.delete();
        }
        return writer;
    }
}
